﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;
using System.Collections;
using System.Reflection;
using XCommon.Types;


namespace XDAL.MySQL
{
    /// <summary>

    /// 基于MySQL的数据层基类

    /// </summary>

    /// <remarks>

    /// 参考于MS Petshop 4.0

    /// </remarks>

    public abstract class MySqlHelper
    {

        #region 数据库连接字符串

        public static readonly string DBConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;

        #endregion

        #region PrepareCommand

        /// <summary>

        /// Command预处理

        /// </summary>

        /// <param name="conn">MySqlConnection对象</param>

        /// <param name="trans">MySqlTransaction对象，可为null</param>

        /// <param name="cmd">MySqlCommand对象</param>

        /// <param name="cmdType">CommandType，存储过程或命令行</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组，可为null</param>

        protected static void PrepareCommand(MySqlConnection conn, MySqlTransaction trans, MySqlCommand cmd, CommandType cmdType, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)

                conn.Open();

            cmd.Connection = conn;

            cmd.CommandText = cmdText;

            if (trans != null)

                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {

                foreach (MySqlParameter parm in cmdParms)

                    cmd.Parameters.Add(parm);

            }

        }

        #endregion

        #region ExecuteNonQuery

        /// <summary>

        /// 执行命令

        /// </summary>

        /// <param name="connectionString">数据库连接字符串</param>

        /// <param name="cmdType">命令类型（存储过程或SQL语句）</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组</param>

        /// <returns>返回受引响的记录行数</returns>

        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {

                PrepareCommand(conn, null, cmd, cmdType, cmdText, cmdParms);

                int val = cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();

                return val;

            }

        }

        public static int ExecuteNonQuery(string cmdText, params MySqlParameter[] cmdParms)
        {
            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = new MySqlConnection(MySqlHelper.DBConnectionString))
            {
                PrepareCommand(conn, null, cmd, CommandType.Text, " SET NAMES UTF8 ; " + cmdText, cmdParms);

                int val = cmd.ExecuteNonQuery();

                cmd.Parameters.Clear();

                return val;

            }
        }

        /// <summary>

        /// 执行命令

        /// </summary>

        /// <param name="conn">Connection对象</param>

        /// <param name="cmdType">命令类型（存储过程或SQL语句）</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组</param>

        /// <returns>返回受引响的记录行数</returns>

        public static int ExecuteNonQuery(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            PrepareCommand(conn, null, cmd, cmdType, cmdText, cmdParms);

            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            return val;

        }

        /// <summary>

        /// 执行事务

        /// </summary>

        /// <param name="trans">MySqlTransaction对象</param>

        /// <param name="cmdType">命令类型（存储过程或SQL语句）</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组</param>

        /// <returns>返回受引响的记录行数</returns>

        public static int ExecuteNonQuery(MySqlTransaction trans, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            PrepareCommand(trans.Connection, trans, cmd, cmdType, cmdText, cmdParms);

            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            return val;

        }

        #endregion

        #region ExecuteScalar

        /// <summary>

        /// 执行命令，返回第一行第一列的值

        /// </summary>

        /// <param name="connectionString">数据库连接字符串</param>

        /// <param name="cmdType">命令类型（存储过程或SQL语句）</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组</param>

        /// <returns>返回Object对象</returns>

        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {

                PrepareCommand(connection, null, cmd, cmdType, cmdText, cmdParms);

                object val = cmd.ExecuteScalar();

                cmd.Parameters.Clear();

                return val;

            }

        }

        /// <summary>

        /// 执行命令，返回第一行第一列的值

        /// </summary>

        /// <param name="connectionString">数据库连接字符串</param>

        /// <param name="cmdType">命令类型（存储过程或SQL语句）</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组</param>

        /// <returns>返回Object对象</returns>

        public static object ExecuteScalar(MySqlConnection conn, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            PrepareCommand(conn, null, cmd, cmdType, cmdText, cmdParms);

            object val = cmd.ExecuteScalar();

            cmd.Parameters.Clear();

            return val;

        }

        #endregion

        #region ExecuteReader


        public static MySqlDataReader ExecuteReader(string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            MySqlConnection conn = new MySqlConnection(DBConnectionString);

            try
            {
                PrepareCommand(conn, null, cmd, CommandType.Text, cmdText, cmdParms);

                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                cmd.Parameters.Clear();

                return dr;

            }

            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>

        /// 执行命令或存储过程，返回MySqlDataReader对象

        /// 注意MySqlDataReader对象使用完后必须Close以释放MySqlConnection资源

        /// </summary>

        /// <param name="connectionString">数据库连接字符串</param>

        /// <param name="cmdType">命令类型（存储过程或SQL语句）</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组</param>

        /// <returns></returns>

        public static MySqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            MySqlConnection conn = new MySqlConnection(connectionString);

            try
            {

                PrepareCommand(conn, null, cmd, cmdType, cmdText, cmdParms);

                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                cmd.Parameters.Clear();

                return dr;

            }

            catch
            {

                conn.Close();

                throw;

            }
        }

        #endregion

        #region ExecuteDataSet

        /// <summary>

        /// 执行命令或存储过程，返回DataSet对象

        /// </summary>

        /// <param name="connectionString">数据库连接字符串</param>

        /// <param name="cmdType">命令类型(存储过程或SQL语句)</param>

        /// <param name="cmdText">SQL语句或存储过程名</param>

        /// <param name="cmdParms">MySqlCommand参数数组(可为null值)</param>

        /// <returns></returns>

        public static DataSet ExecuteDataSet(string connectionString, CommandType cmdType, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {

                PrepareCommand(conn, null, cmd, cmdType, cmdText, cmdParms);

                MySqlDataAdapter da = new MySqlDataAdapter(cmd);

                DataSet ds = new DataSet();

                da.Fill(ds);

                conn.Close();

                cmd.Parameters.Clear();

                return ds;

            }

        }

        #endregion

        public static MySqlParameter[] CreateParameter<T>(T obj)
        {
            List<MySqlParameter> parm = new List<MySqlParameter>();

            Type t = obj.GetType();
            MySqlParameter t_parm = null;
            foreach (PropertyInfo item in t.GetProperties())
            {
                if (item.IsDefined(typeof(DBFileAttribule), false))
                {
                    t_parm = new MySqlParameter("@" + item.Name, item.GetValue(obj, null));
                    parm.Add(t_parm);
                }
            }
            return parm.ToArray();
        }

        public static List<Ps> ReadToList(MySqlDataReader rd)
        {
            List<Ps> list = new List<Ps>();
            Ps ps;
            string fieldName;
            string fieldValue;
            while (rd.Read())
            {
                ps = new Ps();
                for (int i = 0; i < rd.FieldCount; i++)
                {
                    fieldName = rd.GetName(i);
                    fieldValue = rd[i].ToString();
                    ps.Add(fieldName, fieldValue);
                }
                list.Add(ps);
            }
            return list;
        }

        public static List<Ps>[] ReadToLists(MySqlDataReader rd)
        {
            List<List<Ps>> list = new List<List<Ps>>();
            do
            {
                list.Add(ReadToList(rd));
            }
            while (rd.NextResult());
            return list.ToArray();
        }

        public static List<T> ReadToEntity<T>(MySqlDataReader rd) where T : new()
        {
            List<T> list = new List<T>();
            T entity;
            string fieldName;
            Type t = typeof(T);
            Dictionary<string, PropertyInfo> propertys = new Dictionary<string, PropertyInfo>();
            foreach (PropertyInfo item in t.GetProperties())
            {
                if (item.IsDefined(typeof(DBFileAttribule), false))
                {
                    propertys.Add(item.Name, item);
                }
            }
            while (rd.Read())
            {
                entity = new T();

                for (int i = 0; i < rd.FieldCount; i++)
                {
                    fieldName = rd.GetName(i);
                    object fieldValue = rd[i];

                    if (!propertys.ContainsKey(fieldName))
                    {
                        continue;
                    }
                    Type propertyDataType = propertys[fieldName].PropertyType;

                    try
                    {
                        switch (propertyDataType.Name)
                        {
                            case "Int32":
                                propertys[fieldName].SetValue(entity, Convert.ToInt32(fieldValue), null);
                                break;
                            case "DateTime":
                                propertys[fieldName].SetValue(entity, Convert.ToDateTime(fieldValue), null);
                                break;
                            case "Boolean":
                                propertys[fieldName].SetValue(entity, Convert.ToBoolean(fieldValue), null);
                                break;
                            default:
                                propertys[fieldName].SetValue(entity, fieldValue, null);
                                break;
                        }
                    }
                    catch
                    {
                        propertys[fieldName].SetValue(entity, fieldValue.ToString(), null);
                    }

                }
                list.Add(entity);
            }
            return list;
        }
    }//end class

    public class MySQLHelper2 : MySqlHelper
    {
        public static string CheckDBIsCanConn(string connstring)
        {
            try
            {
                string ret = "";
                using (MySqlConnection conn = new MySqlConnection(connstring))
                {
                    conn.Open();
                    ret = "Can Conn";
                }
                return ret;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public static bool ExecuteListCmd(string strSQL, List<MySqlParameter[]> cmds, ref string errmsg)
        {
            bool bRet = false;
            if (cmds.Count > 0)
            {
                MySqlConnection conn = null;
                MySqlTransaction tran = null;
                try
                {
                    conn = new MySqlConnection(MySqlHelper.DBConnectionString);
                    conn.Open();
                    tran = conn.BeginTransaction();
                    foreach (var item in cmds)
                    {
                        bRet = ExecuteNonQuery(conn, tran, strSQL, item) > 0;
                        if (!bRet)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (tran != null) tran.Rollback();
                    errmsg = ex.Message;
                    bRet = false;
                }
                finally
                {
                    if (conn != null && conn.State != ConnectionState.Closed)
                    {
                        conn.Close();
                    }
                }
            }
            return bRet;
        }

        public static int ExecuteNonQuery(MySqlConnection conn, MySqlTransaction trans, string cmdText, params MySqlParameter[] cmdParms)
        {

            MySqlCommand cmd = new MySqlCommand();

            PrepareCommand(conn, trans, cmd, CommandType.Text, cmdText, cmdParms);

            int val = cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            return val;

        }
    }

}
